package com.lvmama.pangolin.timer.processor;



import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.lvmama.pangolin.busi.timer.TimerManagerAssist;
import com.lvmama.pangolin.common.StringTools;
import com.lvmama.pangolin.entity.Timer;
import com.lvmama.pangolin.service.TimerService;
import com.lvmama.pangolin.timer.CommonJob;
import com.lvmama.pangolin.util.SpringContextUtil;


public class TimerMonitor extends CommonJob {

	@Autowired
	private TimerService timerService;
	
	private Logger logger = Logger.getLogger(TimerMonitor.class);
	@Override
	public void runJob(JobExecutionContext context, String parameter)
	{
		try
		{
			logger.info("Timer 监控器开始扫描...");
			if(timerService == null)
			{
				timerService = (TimerService) SpringContextUtil.getBean(TimerService.class);
			}
			Timer timerParam = new Timer();
			List<Timer> timerList =  timerService.queryTimerList(timerParam);
			if(timerList != null && !timerList.isEmpty())
			{
				TimerManagerAssist timerAssist = new TimerManagerAssist();
				Map<String,Object> param = new HashMap<String,Object>();
				String corn = null;
				Calendar calendar = Calendar.getInstance();
				List<Date> sliceList = timerAssist.spiderTimeSliceList(null,"spider_time_config");
				int i = 0;
				for (Timer timer : timerList)
				{
					//重跑
					if(timer.getRun_num() <timer.getRetry_num())
					{
						//非周期性执行任务
						if("1".equals(timer.getExec_mode()))
						{
							
							param.put("timer_id", timer.getTimer_id());
							param.put("timer_status", "0");
							param.put("timer_type", "");
							param.put("run_num", timer.getRun_num()+1);
							param.put("error_desc",  "重跑");
							
							if(sliceList != null && !sliceList.isEmpty() && i<= sliceList.size())
							{
								if(i == sliceList.size())
								{
									i = 0;
								}
								corn = StringTools.generateCorn(sliceList.get(i));
							}
							else
							{
								calendar.add(Calendar.MINUTE, 30);//30分钟后执行
								corn = StringTools.generateCorn(calendar.getTime());
							}
							param.put("corn",  corn);
							timer.setTimer_cron(corn);
							timerAssist.loadValidJob(timer);
							i ++;
							
						}
						else
						{
//							timerAssist.fireJob(timer.getTimer_code());
						}
						
					}
					else
					{
					//挂起
						param.put("timer_id", timer.getTimer_id());
						param.put("timer_status", "4");
						param.put("error_desc",  "重跑次数大于最大重跑次数，任务置成挂起状态！");
						
					}
					param.put("oper_time", new Timestamp(new Date().getTime()));
					timerService.updateTimerByCon(param);
					
				}
				
			}
			logger.info("Timer 监控器完成扫描......");
			
		}catch (Exception e)
		{
			logger.error("更新任务状态失败!",e);
		}
		
		
		
	}

}
